from http.server import HTTPServer, BaseHTTPRequestHandler
import json
from urllib.parse import parse_qs
from typing import Dict, Protocol, List

data = {'result': 'this is a test'}
host = ('localhost', 8888)

class RouteNotificationManager:

    _containers = {}

    def __init__(self):
        pass
    def registered(self,route, cls):

        if route not in _containers:
            _containers[route] = []

        self._containers[route].append(cls)

    def execute(self, route,data):

        if route not in _containers:
            pass

        for item in _containers[route]:
            try:
                item.handler(data)
                print("Hello World!")
            except Exception as e:
                # 异常处理代码
                print(e)


class INotification(Protocol):

    @field.getter
    def route(self):
        pass

    def handler(self,data):
        pass

class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

    @classmethod
    def from_json(cls, json_str):
        # 解析JSON字符串
        data = json.loads(json_str)
        # 使用数据创建类的实例
        return cls(**data)


class Resquest(BaseHTTPRequestHandler):
    # def end_headers(self):
    #     self.send_header('Access-Control-Allow-Origin', '*')
    #     self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
    #     self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
    #     BaseHTTPRequestHandler.end_headers(self)

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()

        # Respond with an empty body to the pre-flight request
        self.wfile.write(b'')

    def do_GET(self):

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()

        json_str = '{"name": "Alice", "age": 30, "city": "New York"}'
        # 使用from_json方法将JSON转换成类的实例
        person = Person.from_json(json_str)

        print(person.name)  # 输出: Alice
        print(person.age)  # 输出: 30
        print(person.city)  # 输出: New York





        route =  self.parseRoute(self.path)
        params = self.parseParams(self.path)


        print('路由地址：' + route)
        print('参数：' + params)
        self.wfile.write(json.dumps(data).encode())

    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))

        print('headers', self.headers)
        print("do post:", self.path, self.client_address, datas)

        self.send_response(400)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def parseRoute(self,route):
        if route.find("?") == -1:
            return  route
        else:
            return route.split("?")[0]

    def parseParams(self,route):
        if route.find("?") == -1:
            return ""
        else:
            return route.split("?")[1]



if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()